<?php
/**
 * Created by PhpStorm.
 * User: Rung-PC
 * Date: 2018/8/8
 * Time: 13:46
 */

namespace app\api\controller;
use app\admin\controller\Common;

class Adminapi extends Common{

    public function __construct(){
        parent::__construct();
        if(!request()->isAjax() && request()->action() != 'upload'){
            die('fuck you!');
        }
    }

    public function addBnr(){
        $data = input('');
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->validate(['size'=>2048000,'ext'=>'jpg,png'])->move('static/banner');
        if($info){
            $data['homeImg'] = str_replace('\\','/',$info->getSaveName());
        }else{
            // 上传失败获取错误信息
            return array('status'=>0,'msg'=>$file->getError());
        }
        $id = db('banner')->insertGetId($data);
        if($id){
            return array('status'=>1,'msg'=>'ok','homeId'=>$id,'homeImg'=>$data['homeImg']);
        }else{
            return array('status'=>0,'msg'=>'未知错误!');
        }
    }

    public function addMenu(){
        $data = input('','','trim');
        $id = db('menu')->insertGetId($data);
        if($id){
            return array('status'=>1,'msg'=>'ok','id'=>$id);
        }else{
            return array('status'=>0,'msg'=>'未知错误!');
        }
    }

    public function upload(){
       $file = request()->file('file');
       $info = $file->validate(['size'=>2048000,'ext'=>'jpg,png'])->move('static/htmlImg');
       if($info){
            $imgUrl = str_replace('\\','/',$info->getSaveName());
            $http = 'http://'.request()->header('host');
            return json(array('status'=>1,'url'=>$http.'/static/htmlImg/'.$imgUrl));
        }else{
            // 上传失败获取错误信息
            return json(array('status'=>0,'msg'=>$file->getError()));
        }
    }

    public function menuhtml(){
        $data = input('');
        $htmlId = db('menu_html')->where(['menuId'=>$data['menuId']])->value('htmlId');
        if($htmlId){
            $result = db('menu_html')->where(['htmlId'=>$htmlId])->update($data);
        }else{
            $result = db('menu_html')->insertGetId($data);
        }
        if($result){
            return array('status'=>1);
        }
        return array('status'=>0);
    }

    public function getHtml(){
        $menuId = input('menuId');
        $htmlContent = db('menu_html')->where(['menuId'=>$menuId])->value('htmlContent');
        return array('status'=>1,'htmlContent'=>$htmlContent);
    }
}